﻿using System.ServiceModel;
using AutoMapper;
using Framework.Exceptions;
using Framework.Exceptions.ServiceExceptions;
using Interfaces.BusinessLogic;
using Interfaces.FilterModels;
using Interfaces.Models;
using Interfaces.Validation;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WCF;
using ServiceInfrastructure.Models.Exceptions;
using ServiceInfrastructure.Models.NewsModels;
using ServiceInfrastructure.Models.NewsModels.FilterModels;
using ServiceInfrastructure.Models.NewsModels.Models;

namespace EconomicInformationServiceWcf
{
    [ExceptionShielding(PolicyNames.NewsInformationPolicy)]
    public class NewsInformationService : INewsInformationService
    {
        private readonly IValidator _validator;
        private readonly IFeedOperationService _feedOperation;
        private readonly IEntityMapper<IFeed, Feed> _mapper;

        public NewsInformationService(IValidator validator, 
            IFeedOperationService feedOperation, 
            IEntityMapper<IFeed, Feed> mapper)
        {
            _validator = validator;
            _feedOperation = feedOperation;
            _mapper = mapper;
        }

        public GetNewsByUrlResponse GetNewsByUrl(GetNewsByUrlRequest request)
        {
            if(request.KeyLink == null)
                throw new FaultException<GeneralFault>(new GeneralFault("Incomplete request arguments"));

            if (request.KeyLink.Url == null)
                throw new FaultException<GeneralFault>(new GeneralFault("Incomplete request arguments"));
          
            
            var keyUri = request.KeyLink.Url;
            var filterModel = request.FilterModel;
            var logicFilterModel = Mapper.DynamicMap<NewsFilterModel, INewsFilterModel>(filterModel);
            var validationResult = _validator.Validate(logicFilterModel);
            
            if (!validationResult.IsValid)
                throw new ValidationException("Validation error in GetNewsByUrl method",validationResult);
            
            var result = _feedOperation.GetDataByUrl(keyUri, logicFilterModel);

            var response = new GetNewsByUrlResponse {SourceFeed =_mapper.Map(result)};

            return response;
        }

        public GetNewsByUrlsResponse GetNewsByUrls(GetNewsByUrlsRequest request)
        {
            throw new System.NotImplementedException();
        }
    }
}
